package com.ujiuye.web;


import com.ujiuye.entity.UserInfo;
import com.ujiuye.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取响应输出流(字符输出流-->向页面输出文本信息)
        PrintWriter pw = resp.getWriter();
        //获取页面数据  用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //获取记住密码选项
        String save = req.getParameter("save");
        UserService us = new UserService();
        //调用service层中登录的方法
        UserInfo userInfo = us.userLogin(username, password);
        if(userInfo!=null){
            //登录成功-->判断是否勾选记住密码-->查询学生信息
            if("checkOn".equals(save)){
                HttpSession session1=req.getSession();
                session1.setAttribute("userInfo",userInfo);
                //勾选-->保存账号密码
                Cookie c1 = new Cookie("username",userInfo.getUsername());
                Cookie c2 = new Cookie("password",userInfo.getPwd());
                //设置生存时间
                c1.setMaxAge(60*60*24*7);
                c2.setMaxAge(60*60*24*7);
                //添加到浏览器
                resp.addCookie(c1);
                resp.addCookie(c2);
            }
            //将用户信息保存到session中

                                                                                                                                                                                                                    HttpSession session = req.getSession();
            session.setAttribute("userInfo",userInfo);
            //转发
            req.getRequestDispatcher("queryStuByPage").forward(req,resp);
        }else{
            //登录失败-->给提示信息
            pw.println("用户名或者密码错误,请重新<a href='login.jsp'>登录</a>");
        }
    }

}
